from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.ser import *


# Create your views here.
# 查询班级及班级下的课程
class ShowCourse(APIView):
    def get(self, request):
        cla = Sclass.objects.all()
        ser = SclassSer(cla, many=True)
        return Response({"code": 200, 'list': ser.data})


class Reg(APIView):
    def post(self, request):
        ser = StuSer(data=request.data)
        if ser.is_valid():
            ser.save()
            stu = Stu.objects.filter(username=request.data.get('username')).first()
            return Response({'code': 200, 'id': stu.id, 'name': stu.name})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        id = request.GET.get('id')
        stu = Stu.objects.filter(id=id).first()
        ser = SclassSer(stu)
        return Response({'coe': 200, 'stu': ser.data})


class ChangeClass(APIView):
    def post(self, request):
        id = request.data.get('id')
        stu = Stu.objects.filter(id=id).first()
        ser = ShowStuSer(stu)
        s = ser.data
        if s['cla']['type'] == 1:
            cla = Sclass.objects.filter(type=2).first()
            stu.cla_id = cla.id
            stu.save()
        elif s['cla']['type'] == 2:
            cla = Sclass.objects.filter(type=3).first()
            stu.cla_id = cla.id
            stu.save()
        else:
            return Response({'code': 20012})
